package br.ucb.indica.DAO;

import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.ucb.indica.negocio.ComentarioBean;

public class ComentarioDAO {
	
	private Connection con;
	
	public ComentarioDAO() throws SQLException {
		this.con = ConnectionFactory.getConnection();
	}

	public int incluir(ComentarioBean comentario) throws SQLException {
		if (comentario == null) return 0;
		PreparedStatement stmt = con.prepareStatement("INSERT INTO comentario (comentario_comentario, id_erro) values (?, ?)");
		stmt.setString(1, comentario.getComentario());	
		stmt.setLong(2, comentario.getErro().getId());		
		int retorno = stmt.executeUpdate();
		stmt.close();
		return retorno;
	}
	
	public ComentarioBean consultar(Long id) throws SQLException, NoSuchAlgorithmException {
		PreparedStatement stmt = this.con.prepareStatement("SELECT * FROM comentario WHERE id_comentario=?");
		stmt.setLong(1, id);
		ResultSet rs = stmt.executeQuery();
		ComentarioBean comentario = null;
		if (rs.next()) {
			comentario = new ComentarioBean();
			comentario.setId(rs.getLong("id_comentario"));
			comentario.setComentario(rs.getString("comentario_comentario"));
			comentario.setErro(new ErroDAO().consultar(rs.getLong("id_erro")));		
		}
		rs.close();
		stmt.close();
		return comentario;	
	}		
	
	public List<ComentarioBean> listar() throws SQLException, NoSuchAlgorithmException {
		PreparedStatement stmt = this.con.prepareStatement("SELECT * FROM comentario");
		ResultSet rs = stmt.executeQuery();
	    List<ComentarioBean> comentarios = new ArrayList<ComentarioBean>();
	    while (rs.next()) {
		    ComentarioBean comentario = new ComentarioBean();
		    comentario.setId(rs.getLong("id_comentario"));
		    comentario.setComentario(rs.getString("comentario_comentario"));
		    comentario.setErro(new ErroDAO().consultar(rs.getLong("id_erro")));
		    comentarios.add(comentario);
		}
		rs.close();
		stmt.close();
		return comentarios;	
	}
	
	public int alterar(ComentarioBean comentario) throws SQLException {
		if (comentario == null) return 0;
		PreparedStatement stmt = this.con.prepareStatement("UPDATE comentario SET comentario_comentario=?, id_erro=? WHERE id_comentario=?");
		stmt.setString(1, comentario.getComentario());
		stmt.setLong(2, comentario.getErro().getId());
		int retorno = stmt.executeUpdate();
		stmt.close();
		return retorno;
	}	

	public int excluir(ComentarioBean comentario) throws SQLException {
		if (comentario == null) return 0;
		PreparedStatement stmt = this.con.prepareStatement("DELETE FROM comentario WHERE id_comentario=?");
		stmt.setLong(1, comentario.getId());
		int retorno = stmt.executeUpdate();
		stmt.close();
		return retorno;
	}	
	
}
